package com.lmpop.trade.backupDB;

import com.lmpop.frame.dao.JdbcDbm;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Set;

public class JDBCExceute
{
  public ArrayList excute(String sqlstr)
  {
    Connection connetcion = null;
    try {
      connetcion = new JdbcDbm().getConnection();
      connetcion.setAutoCommit(true);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    ArrayList datalist = new ArrayList();
    ResultSet rs = null;
    if (sqlstr.equals(""))
      return null;
    try {
      System.out.println(sqlstr);
      rs = connetcion.createStatement().executeQuery(sqlstr);
      Hashtable map = getDataColl(rs);
      Object[] keys = map.keySet().toArray();
      while (rs.next()) {
        Hashtable dataSet = new Hashtable();
        for (int i = 0; i < keys.length; i++) {
          dataSet.put(keys[i].toString().toLowerCase(), rs.getString(keys[i].toString()));
        }
        datalist.add(dataSet);
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        connetcion.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return datalist;
  }

  public int CRUD(String sqlstr)
  {
    Connection connetcion = null;
    try {
      connetcion = new JdbcDbm().getConnection();
      connetcion.setAutoCommit(true);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    try {
      connetcion.createStatement().execute(sqlstr);
      return 0;
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return -1;
    }
    finally
    {
      try
      {
        if (!connetcion.isClosed())
          connetcion.close();
      }
      catch (SQLException e)
      {
        e.printStackTrace();
      }
    }
  }

  public Hashtable getDataColl(ResultSet rs)
  {
    Hashtable mapcoll = new Hashtable();
    try {
      ResultSetMetaData rsmd = rs.getMetaData();

      for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        String filedName = rsmd.getColumnName(i);
        String fileType = rsmd.getColumnTypeName(i);
        mapcoll.put(filedName, fileType);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return mapcoll;
  }

  public boolean saveOrUpdate(String sqlstr)
  {
    Connection connetcion = null;
    try {
      connetcion = new JdbcDbm().getConnection();
      connetcion.setAutoCommit(true);
      connetcion.createStatement().execute(sqlstr);
      return true;
    }
    catch (Exception e)
    {
    }
    return false;
  }
}